from flask import request

from threading import Thread
import websocket
import requests

from .. import websockets

# ============================================ 类和方法定义 =======================================================
class WSClient():
    def __init__(self,fws,fname):
        self.fname = fname
        self.fws = fws

    def test_websocket(self):
        def on_open(ws):
            ws.send(self.fname)

        def on_message(ws,message):
            self.fws.send(message)

        def on_error(ws, error):
            print(error)

        def on_close(ws):
            print("### closed ###")

        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("ws://192.168.250.13:8002/progress",
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)

        ws.on_open = on_open  
        ws.run_forever()
    
def ws_worker(fws,fname):
    '''
    具体做ws转发的工人
    '''
    ws = WSClient(fws,fname)
    ws.test_websocket()

# ============================================ views =======================================================

@main_blueprint.route('/style_migration',methods=['POST',])
def sm_views():
    '''
    接收图片并转发至算法服务器
    '''
    content_img = request.files['content_img']
    style_id = request.form.get('style_id',None)
    
    url = "http://192.168.250.13:8002/style_migration"

    files = {'content_img':(content_img.filename,content_img)}
    data = {'style_id':style_id}

    res = requests.post(url,data=data,files=files)
    print(res)
    print(res.text)
    return res.content
    
@websockets.route('/getProgress')
def ws_getProgress(ws):
    '''
    websocket转发路由
    '''
    fname = ws.receive()
    
    # 启用一个线程做websocket转发
    t = Thread(target=ws_worker,args=(ws,fname,))
    t.setDaemon(True)
    t.start()